<template>
  <div>
    <el-form ref="form" :model="formData" :rules="rules">
      <!-- HOST -->
      <el-form-item v-if="hostVisible" :label-width="labelWidth" label="HOST" prop="host">
        <el-input v-model="formData.host" :disabled="formDisabledByStartState" placeholder="请输入host"/>
      </el-form-item>

      <!-- PORT -->
      <el-form-item v-if="portVisible" :label-width="labelWidth" label="PORT" prop="port">
        <el-input v-model="formData.port" :disabled="formDisabledByStartState" placeholder="请输入port"/>
      </el-form-item>

      <div v-if="addressesVisible" style="margin-bottom: 20px">
        <el-row  v-for="(item, index) in formData.addresses" :style="{'padding-left': `${labelWidth}`}">
          <el-col :span="22">
            <el-collapse>
              <el-collapse-item :title="item.clientName" :name="item.clientName">
                <!-- HOST -->
                <el-form-item
                  :label-width="labelWidth"
                  label="HOST"
                  :prop="`addresses.${index}.host`"
                  :rules="rules.addresses.host"
                >
                  <el-input v-model="item.host" :disabled="formDisabledByStartState" placeholder="请输入host"/>
                </el-form-item>

                <!-- PORT -->
                <el-form-item
                  :label-width="labelWidth"
                  label="PORT"
                  :prop="`addresses.${index}.port`"
                  :rules="rules.addresses.port"
                >
                  <el-input v-model="item.port" :disabled="formDisabledByStartState" placeholder="请输入port"/>
                </el-form-item>
              </el-collapse-item>
            </el-collapse>
          </el-col>

          <el-col :span="2" style="margin-top: 8px; padding-left: 20px">
            <!-- 删除配置项 -->
            <el-button :disabled="formDisabledByStartState" @click="handleDeleteAddress(index)" type="text">
              <i class="el-icon-remove-outline enum-add-remove-icon"/>
            </el-button>
          </el-col>
        </el-row>

        <el-row :style="{'padding-left': `${labelWidth}`, 'margin-top': '20px'}">
          <el-button
            style="width: 100%"
            icon="el-icon-plus"
            size="medium"
            :disabled="formDisabledByStartState"
            @click="handleAddTcpClientAddress"
            v-hasPermi="['iot:network:add']"
          >新增</el-button>
        </el-row>
      </div>

      <!-- 证书 -->
      <el-form-item v-if="certIdVisible" :label-width="labelWidth" label="证书" prop="certId">
        <el-select
          v-model="formData.certId"
          clearable
          placeholder="请选择证书"
          :disabled="formDisabledByStartState" class="select-width"
        >
          <el-option v-for="dict in certificates" :key="dict.id" :label="dict.certificateName" :value="dict.id"/>
        </el-select>
      </el-form-item>

      <!-- 开启ssl -->
      <el-form-item v-if="sslVisible" :label-width="labelWidth" label="开启SSL" prop="ssl">
        <el-radio-group v-model="formData.ssl" :disabled="formDisabledByStartState">
          <el-radio :label="true">是</el-radio>
          <el-radio :label="false">否</el-radio>
        </el-radio-group>
      </el-form-item>

      <!-- 线程数 -->
      <el-form-item v-if="threadsVisible" :label-width="labelWidth" label="线程数" prop="threads">
        <el-input v-model="formData.threads" :disabled="formDisabledByStartState" placeholder="请输入线程数"/>
      </el-form-item>

      <!-- clientId -->
      <el-form-item v-if="clientIdVisible" :label-width="labelWidth" label="clientId" prop="clientId">
        <el-input
          v-model="formData.clientId"
          :disabled="formDisabledByStartState"
          placeholder="请输入clientId"
        />
      </el-form-item>

      <!-- 拆包规则 -->
      <el-form-item v-if="parserTypeVisible" :label-width="labelWidth" label="拆包规则" prop="parserType">
        <el-select
          v-model="formData.parserType"
          :disabled="formDisabledByStartState"
          placeholder="请选择拆包规则"
          class="select-width"
        >
          <el-option
            v-for="dict in dict.type.iot_network_parser_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <!-- 分隔符 -->
      <el-form-item v-if="delimitedVisible" :label-width="labelWidth" label="分隔符" prop="parserConfiguration.delimited">
        <el-input
          v-model="formData.parserConfiguration.delimited"
          :disabled="formDisabledByStartState"
          placeholder="请输入分隔符"
        />
      </el-form-item>

      <!-- 脚本 -->
      <el-form-item v-if="scriptVisible" :label-width="labelWidth" label="脚本">
        <editor
          :disabled="formDisabledByStartState"
          v-model="formData.parserConfiguration.script"
          @init="editorInit"
          lang="javascript"
          theme="chrome"
          height="300"
          :options="editorOptions"
        />
      </el-form-item>

      <!-- 长度值 -->
      <el-form-item v-if="sizeVisible" :label-width="labelWidth" label="长度值" prop="parserConfiguration.size">
        <el-input
          v-model="formData.parserConfiguration.size"
          :disabled="formDisabledByStartState"
          placeholder="请输入长度值"
        />
      </el-form-item>

      <!-- THS -->
      <el-form-item v-if="tlsVisible" :label-width="labelWidth" label="TLS" prop="tls">
        <el-radio-group v-model="formData.tls">
          <el-radio :label="true">是</el-radio>
          <el-radio :label="false">否</el-radio>
        </el-radio-group>
      </el-form-item>

      <!-- 用户名 -->
      <el-form-item v-if="userNameVisible" :label-width="labelWidth" label="用户名" prop="userName">
        <el-input v-model="formData.userName" :disabled="formDisabledByStartState" placeholder="请输入用户名"/>
      </el-form-item>

      <!-- 密码 -->
      <el-form-item v-if="passwordVisible" :label-width="labelWidth" label="密码" prop="password">
        <el-input v-model="formData.password" :disabled="formDisabledByStartState" placeholder="请输入密码"/>
      </el-form-item>

      <!-- 最大消息长度 -->
      <el-form-item v-if="informationVisible" :label-width="labelWidth" label="最大消息长度" prop="information">
        <el-input
          v-model="formData.information"
          :disabled="formDisabledByStartState"
          placeholder="请输入最大消息长度"
        />
      </el-form-item>

    </el-form>
    <!-- clientName添加表单 -->
    <network-client-name @submit="handleSubmitClientName" ref="networkClientName"/>
  </div>

</template>

<script>
import Editor from 'vue2-ace-editor'
import { queryCertificate } from '@/api/iot/certificate'
import NetworkClientName from './networkClientName'

export default {
  name: 'NetworkConfiguration',
  dicts: [
    'iot_network_parser_type'
  ],
  components: {
    Editor,
    NetworkClientName,
  },
  props: {
    formData: {
      type: Object,
      default: true
    },
    labelWidth: {
      type: String,
      default: true
    },
    startState: {
      type: String,
      default: true
    },
    networkType: {
      type: String
    }
  },
  computed: {
    formDisabledByStartState() {
      const disabled = this.startState === 'enabled'
      this.editorOptions.readOnly = disabled
      return disabled
    }
  },
  watch: {
    networkType: {
      handler(type) {
        this.visibleByNetwork(type)
      },
      immediate: true
    },
    'formData.parserType': {
      handler(type) {
        this.visibleByParserType(type)
      },
      immediate: true
    }
  },
  data() {
    const hostRule = [{
      required: true,
      validator: (rule, value, callback) => {
        if (!value) {
          callback(new Error('请输入IP地址'))
          return
        }
        const ipPattern = /^((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)$/
        if (!ipPattern.test(value)) {
          callback(new Error('请输入正确的IP地址'))
          return
        }
        callback()
      }, trigger: 'change'
    }]

    const portRule = [{
      required: true,
      validator: (rule, value, callback) => {
        if (!value) {
          callback(new Error('请输入PORT'))
          return
        }
        const portPattern = /^([1-9]|[1-9]\d{1,3}|[1-5]\d{4}|6[0-4]\d{3}|65[0-4]\d{2}|655[0-2]\d|6553[0-5])$/
        if (!portPattern.test(value)) {
          callback(new Error('请输入正确的PORT'))
          return
        }
        callback()
      },
      trigger: 'change'
    }]

    return {
      // 表单校验
      rules: {
        host: hostRule,
        port: portRule,
        parserType: [
          { required: true, message: '拆包规则不能为空', trigger: 'change' }
        ],
        ssl: [
          { required: true, message: 'ssl不能为空', trigger: 'change' }
        ],
        addresses: {
          host: hostRule,
          port: portRule,
        }
      },
      // 代码编辑器配置
      editorOptions: {
        // 设置代码编辑器的样式
        enableBasicAutocompletion: true, //启用基本自动完成
        enableSnippets: true, // 启用代码段
        enableLiveAutocompletion: true, //启用实时自动完成
        tabSize: 2, //标签大小
        fontSize: 14, //设置字号
        showPrintMargin: false //去除编辑器里的竖线
      },

      // 证书
      certificates: [],

      // 线程数输入框默认隐藏
      threadsVisible: false,
      // host输入框默认隐藏
      hostVisible: false,
      // port输入框默认隐藏
      portVisible: false,
      // 地址输入框默认隐藏（ip地址和port集合）
      addressesVisible: false,
      // tls单选框默认隐藏
      tlsVisible: false,
      // 证书输入狂默认隐藏
      certIdVisible: false,
      // 最大消息长度默认隐藏
      informationVisible: false,
      // clientId默认隐藏
      clientIdVisible: false,
      // 用户名默认隐藏
      userNameVisible: false,
      // 密码默认隐藏
      passwordVisible: false,
      // ssl单选框默认隐藏
      sslVisible: false,
      // 拆包规则默认隐藏
      parserTypeVisible: false,
      // 分隔符默认隐藏
      delimitedVisible: false,
      // 脚本默认隐藏
      scriptVisible: false,
      // 长度值默认隐藏
      sizeVisible: false

    }
  },
  created() {
    // 获取证书信息
    this.getCertificates()
  },
  methods: {
    async handleSubmit() {
      if (this.networkType === 'TCP_CLIENT' && this.formData.addresses.length === 0) {
        this.$modal.msgWarning('请新整客户端HOST和PORT')
        return false;
      }
      let result;
      await this.$refs['form'].validate(valid => result = valid)
      return result;
    },
    //脚本触发事件
    editorInit() {
      require('brace/ext/language_tools') // language extension prerequsite...
      require('brace/mode/javascript')    // language
      require('brace/theme/chrome')
      require('brace/snippets/javascript') // snippet
    },

    /**
     * 根据组件类型显示隐藏表单
     * @param type 组件类型
     */
    visibleByNetwork(type) {
      if (!type) {

        // 地址输入框隐藏（ip地址和port集合）
        this.addressesVisible = false
        // 隐藏 线程数输入框默认
        this.threadsVisible = false
        // 隐藏 host输入框
        this.hostVisible = false
        // 隐藏 port输入框
        this.portVisible = false
        // 隐藏 tls单选框
        this.tlsVisible = false
        // 隐藏 证书输入框
        this.certIdVisible = false
        // 隐藏 最大消息长度
        this.informationVisible = false
        // 隐藏 clientId
        this.clientIdVisible = false
        // 隐藏 用户名
        this.userNameVisible = false
        // 隐藏 密码
        this.passwordVisible = false
        // 隐藏 ssl单选框
        this.sslVisible = false
        // 隐藏 拆包规则输入框
        this.parserTypeVisible = false
        // 隐藏 分隔符输入框
        this.delimitedVisible = false

      } else if (type === 'MQTT_SERVER') {

        // 显示 线程数输入框
        this.threadsVisible = true
        // 显示 host输入框
        this.hostVisible = true
        // 显示 port输入框
        this.portVisible = true
        // 显示 tls单选框
        this.tlsVisible = true
        // 显示 证书输入框
        this.certIdVisible = true
        // 显示 最大消息长度
        this.informationVisible = true
        // 地址输入框隐藏（ip地址和port集合）
        this.addressesVisible = false
        // 隐藏 clientId
        this.clientIdVisible = false
        // 隐藏 用户名
        this.userNameVisible = false
        // 隐藏 密码
        this.passwordVisible = false
        // 隐藏 ssl单选框
        this.sslVisible = false
        // 隐藏 拆包规则输入框
        this.parserTypeVisible = false
        // 隐藏 分隔符输入框
        this.delimitedVisible = false

      } else if (type === 'MQTT_CLIENT') {
        //显示 clientId 输入框
        this.clientIdVisible = true
        // 显示 host输入框
        this.hostVisible = true
        // 显示 port输入框
        this.portVisible = true
        // 显示 tls单选框
        this.tlsVisible = true
        // 显示 证书输入框
        this.certIdVisible = true
        // 显示 最大消息长度
        this.informationVisible = true
        // 显示 用户名
        this.userNameVisible = true
        //显示 密码
        this.passwordVisible = true
        // 地址输入框隐藏（ip地址和port集合）
        this.addressesVisible = false
        // 隐藏 ssl单选框
        this.sslVisible = false
        // 隐藏 拆包规则输入框
        this.parserTypeVisible = false
        // 隐藏 分隔符输入框
        this.delimitedVisible = false
        // 隐藏 线程数输入框
        this.threadsVisible = false

      } else if (type === 'TCP_SERVER' || type === 'TCP_CLIENT') {

        if (type === 'TCP_SERVER') {
          // 显示 host输入框
          this.hostVisible = true
          // 显示 port输入框
          this.portVisible = true
          // 地址输入框隐藏（ip地址和port集合）
          this.addressesVisible = false
        }else {
          // 地址输入框显示（ip地址和port集合）
          this.addressesVisible = true
          // 隐藏 host输入框
          this.hostVisible = false
          // 隐藏 port输入框
          this.portVisible = false
        }

        // 开启 ssl单选框
        this.sslVisible = true
        // 显示 证书输入框
        this.certIdVisible = true
        // 显示 拆包规则输入框
        this.parserTypeVisible = true
        // 隐藏 线程数输入框默认
        this.threadsVisible = false
        // 隐藏 tls单选框
        this.tlsVisible = false
        // 隐藏 clientId
        this.clientIdVisible = false
        // 隐藏 用户名
        this.userNameVisible = false
        // 隐藏 密码
        this.passwordVisible = false
        // 隐藏 最大消息长度
        this.informationVisible = false
      }

    },

    /**
     * 根据拆包规则类型显示隐藏表单
     * @param type 拆包规则类型
     */
    visibleByParserType(type) {
      if (!type) {
        // 隐藏 分隔符输入框
        this.delimitedVisible = false
        // 隐藏 脚本
        this.scriptVisible = false
        // 隐藏 长度值
        this.sizeVisible = false
      } else if (type === 'delimited') {
        //说明拆包规则选择的是  分隔符

        // 显示 分隔符输入框
        this.delimitedVisible = true
        // 隐藏 脚本
        this.scriptVisible = false
        // 隐藏 长度值
        this.sizeVisible = false
      } else if (type === 'script') {
        //说明拆包规则选择的是  脚本

        // 显示 脚本
        this.scriptVisible = true
        // 隐藏 分隔符输入框
        this.delimitedVisible = false
        // 隐藏 长度值
        this.sizeVisible = false
      } else if (type === 'fixed_length') {
        //说明拆包规则选择的是  固定长度
        // 显示 长度值
        this.sizeVisible = true
        // 隐藏 分隔符输入框
        this.delimitedVisible = false
        // 隐藏 脚本
        this.scriptVisible = false
      } else {
        //说明拆包规则选择的是  不处理
        // 隐藏 分隔符输入框
        this.delimitedVisible = false
        // 隐藏 脚本
        this.scriptVisible = false
        // 隐藏 长度值
        this.sizeVisible = false
      }

    },

    /** 获取证书信息 */
    getCertificates() {
      queryCertificate().then(({ data }) => {
        this.certificates = data || []
      })
    },

    /** 删除客户端地址 */
    handleDeleteAddress(index) {
      //删除数组中的一条数据，
      this.formData.addresses.splice(index, 1)
    },
    /** 增加配置的提交按钮 */
    handleSubmitClientName(clientName) {
      this.formData.addresses.push({
        clientName: clientName,
        host: '0.0.0.0',
      })
    },
    /** 新增tcp client配置按钮操作 */
    handleAddTcpClientAddress() {
      // 打开服务id添加页面
      this.$refs.networkClientName.handleOpen()
    },
  }
}
</script>

<style scoped>
</style>
